package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private HttpServletRequest request;

    @PostMapping("/login")
    public R login(@RequestBody Employee employee) {
        R r = employeeService.login(employee);
        if (r.getCode() == 1) {
            HttpSession session = request.getSession();
            session.setAttribute("employee", ((Employee) r.getData()).getId());
        }
        return r;
    }

    @PostMapping("/logout")
    public R logout() {
        //清除用户session
        HttpSession session = request.getSession();
        session.invalidate();

        return R.success("退出成功");
    }

    @PostMapping
    public R add(@RequestBody Employee employee) {
        if (employee == null) {
            return R.error("参数异常");
        }
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());

        HttpSession session = request.getSession();
        Long userid = (Long) session.getAttribute("employee");

        if (userid == null) {
            return R.error("请先登录");
        }

//        employee.setCreateUser(userid);
//        employee.setUpdateUser(userid);

        employeeService.save(employee);

        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R findPage(Integer page, Integer pageSize, String name) {
        R r = employeeService.findPage(page, pageSize, name);
        return r;
    }

    @PutMapping
    public R updateStatus(@RequestBody Employee employee){
        HttpSession session = request.getSession();
        Long empid =(Long) session.getAttribute("employee");

        employee.setUpdateUser(empid);
        employee.setUpdateTime(LocalDateTime.now());
          R r = employeeService.updateStatus(employee);
        return r;

    }
    @GetMapping("/{id}")
    public R fingById(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        return R.success(employee);
    }
}
